<template>
  <div class="m-switch" @click.stop="toggle">
    <span class="switch" :class="{'switch-on' : checked,'switch-disabled':disabled}" :value="value"></span>
    <div v-if="value&&!disabled" class="active">{{activeText}}</div>
    <div v-if="!value&&!disabled" class="inactive">{{inactiveText}}</div>
  </div>
</template>

<script>


export default {
  data () {
    return {
      checked: this.value
    }
  },
  props: {
    value: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    activeText: {
      type: String,
      default: '是'
    },
    inactiveText: {
      type: String,
      default: '否'
    }
  },

  methods: {
    toggle () {
      // 是否可点击
      if (!this.disabled) {
        this.checked = !this.checked;
        this.$emit('input', this.checked);
      }
    }
  },
  watch: {
    value () {
      this.checked = this.value;
    }
  }
}
</script>

<style lang="less" scoped>
.m-switch {
  position: relative;
  //   font-weight: bold;
  cursor: pointer;
  width: 40px;
  height: 20px;
  .switch {
    display: block;
    position: relative;
    width: 40px;
    height: 20px;
    border: 1px solid #ff4949;
    outline: 0;
    border-radius: 10px;
    box-sizing: border-box;
    background-color: #ff4949;
    transition: background-color 0.1s, border 0.1s;
    cursor: pointer;
    &:before {
      content: " ";
      position: absolute;
      top: 0;
      left: 0;
      width: 38px;
      height: 18px;
      border-radius: 9px;
      background-color: #ff4949;
      transition: transform 0.35s cubic-bezier(0.45, 1, 0.4, 1);
    }
    &:after {
      content: " ";
      position: absolute;
      top: 0;
      left: 0;
      width: 18px;
      height: 18px;
      border-radius: 9px;
      background-color: #ffffff;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
      transition: transform 0.35s cubic-bezier(0.4, 0.4, 0.25, 1.35);
    }
  }
  .switch-on {
    border-color: #13ce66;
    background-color: #13ce66;
    &:before {
      border-color: #13ce66;
      background-color: #13ce66;
    }
    &:after {
      transform: translateX(20px);
    }
  }
  .switch-disabled {
    border-color: #dcdfe6;
    background-color: #dcdfe6;
    &:before {
      border-color: #dcdfe6;
      background-color: #dcdfe6;
    }
    &:after {
      transform: translateX(20px);
    }
  }
  .active {
    position: absolute;
    left: 5px;
    top: 0;
    line-height: 20px;
    font-size: 12px;
    color: #fff;
  }
  .inactive {
    position: absolute;
    right: 5px;
    top: 0;
    line-height: 20px;
    font-size: 12px;
    color: #fff;
  }
}
</style>